import React, { useState, useRef, useEffect } from 'react';
import {
  View,
  StyleSheet,
  TouchableOpacity,
  ScrollView,
  StatusBar,
  TextInput,
  KeyboardAvoidingView,
  Platform,
  FlatList,
  Alert,
} from 'react-native';
import Icon from 'react-native-vector-icons/Ionicons';
import AntDesign from 'react-native-vector-icons/AntDesign';
import MaterialIcons from 'react-native-vector-icons/MaterialIcons';
import { useNavigation } from '@react-navigation/native';
import { 
  ResponsiveContainer, 
  ResponsiveText,
  scale,
  Sizes
} from '../../components';

// WebSocket server endpoint
const WS_ENDPOINT = 'ws://172.20.10.2:8080';

// Interface for message objects
interface Message {
  id: string;
  text: string;
  isSent: boolean;
  timestamp: string;
  fromUserId?: string;
  fromUserType?: string;
}

// Initial greeting message
const initialMessages: Message[] = [
  {
    id: '1',
    text: '您好，有什么可以帮助您的？您可以选择自动回复或人工服务。',
    isSent: false,
    timestamp: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }),
  },
];

// Automated responses for demo
const autoResponses = [
  '感谢您的提问，让我为您查询相关信息。',
  '您的问题我们会尽快处理，请您稍等。',
  '您好，这个问题我需要向相关部门确认，请稍等片刻。',
  '您好，请问还有其他我可以帮助您的吗？',
  '如果您对我们的服务满意，希望您可以给我们好评哦！',
];

const ChatScreen: React.FC = () => {
  const [messages, setMessages] = useState<Message[]>(initialMessages);
  const [inputText, setInputText] = useState('');
  const [isHumanAgent, setIsHumanAgent] = useState(false);
  const [ws, setWs] = useState<WebSocket | null>(null);
  const [userId, setUserId] = useState<string>('');
  const [connected, setConnected] = useState(false);
  const [isServiceRole, setIsServiceRole] = useState(false);
  const flatListRef = useRef<FlatList>(null);
  const navigation = useNavigation();

  // Initialize WebSocket connection
  useEffect(() => {
    if (isHumanAgent) {
      connectWebSocket();
    }
    
    return () => {
      if (ws) {
        ws.close();
      }
    };
  }, [isHumanAgent]);

  // Connect to WebSocket server
  const connectWebSocket = () => {
    try {
      const socket = new WebSocket(WS_ENDPOINT);
      
      socket.onopen = () => {
        console.log('WebSocket connected');
        setConnected(true);
        setWs(socket);
        
        // 明确设置用户类型
        socket.send(JSON.stringify({
          type: 'setUserType',
          userType: isServiceRole ? 'service' : 'customer'
        }));
        
        // Add connecting message
        setMessages(prev => [...prev, {
          id: Date.now().toString(),
          text: isServiceRole 
            ? '已连接为客服角色，等待用户连接...' 
            : '正在连接人工客服，请稍等...',
          isSent: false,
          timestamp: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }),
        }]);
      };
      
      socket.onmessage = (event) => {
        const data = JSON.parse(event.data);
        console.log('Received message:', data);
        
        switch (data.type) {
          case 'register':
            setUserId(data.userId);
            setMessages(prev => [...prev, {
              id: Date.now().toString(),
              text: isServiceRole 
                ? `已连接为客服，您的ID: ${data.userId}`
                : `已连接到客服，您的会话ID: ${data.userId}`,
              isSent: false,
              timestamp: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }),
            }]);
            break;
            
          case 'history':
            if (data.messages && data.messages.length > 0) {
              const historyMessages = data.messages.map((msg: any) => ({
                id: Date.now() + Math.random().toString(),
                text: msg.message,
                isSent: (isServiceRole && msg.fromUserType === 'service') || 
                        (!isServiceRole && msg.fromUserType === 'customer'),
                timestamp: msg.timestamp,
                fromUserId: msg.fromUserId,
                fromUserType: msg.fromUserType,
              }));
              setMessages(prev => [...prev, ...historyMessages]);
            }
            break;
            
          case 'message':
            // Message is from the other party
            const isFromMe = (isServiceRole && data.fromUserType === 'service') || 
                           (!isServiceRole && data.fromUserType === 'customer');
            
            setMessages(prev => [...prev, {
              id: Date.now().toString(),
              text: data.message,
              isSent: isFromMe,
              timestamp: data.timestamp || new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }),
              fromUserId: data.fromUserId,
              fromUserType: data.fromUserType,
            }]);
            break;
        }
      };
      
      socket.onerror = (error) => {
        console.error('WebSocket error:', error);
        Alert.alert('连接错误', '无法连接到客服系统，请稍后再试。');
        setIsHumanAgent(false);
      };
      
      socket.onclose = () => {
        console.log('WebSocket closed');
        setConnected(false);
        setWs(null);
        
        // If it was closed unexpectedly while in human agent mode
        if (isHumanAgent) {
          setMessages(prev => [...prev, {
            id: Date.now().toString(),
            text: '聊天连接已断开',
            isSent: false,
            timestamp: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }),
          }]);
          setIsHumanAgent(false);
        }
      };
      
    } catch (error) {
      console.error('Error connecting to WebSocket:', error);
      Alert.alert('连接错误', '无法连接到客服系统，请稍后再试。');
      setIsHumanAgent(false);
    }
  };

  // Handle back button
  const handleBack = () => {
    navigation.goBack();
  };

  // Send message
  const handleSend = () => {
    if (inputText.trim() === '') return;
    
    // Create user message
    const newMessage: Message = {
      id: Date.now().toString(),
      text: inputText,
      isSent: true,
      timestamp: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }),
      fromUserType: isServiceRole ? 'service' : 'customer'
    };
    
    setMessages(prev => [...prev, newMessage]);
    
    // Special handling for "人工服务" message
    if (inputText.trim() === '人工服务' && !isHumanAgent) {
      setIsHumanAgent(true);
      setInputText('');
      return;
    }
    
    setInputText('');
    
    if (isHumanAgent && ws && ws.readyState === WebSocket.OPEN) {
      // Send to WebSocket if human agent mode is active
      ws.send(JSON.stringify({
        type: 'message',
        message: inputText,
        fromUserType: isServiceRole ? 'service' : 'customer',
        timestamp: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
      }));
    } else {
      // Otherwise use automated responses
      setTimeout(() => {
        const randomResponse = autoResponses[Math.floor(Math.random() * autoResponses.length)];
        const responseMessage: Message = {
          id: (Date.now() + 1).toString(),
          text: randomResponse,
          isSent: false,
          timestamp: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }),
          fromUserType: 'service'
        };
        
        setMessages(prev => [...prev, responseMessage]);
      }, 1000);
    }
  };

  // Toggle between human agent and AI mode
  const toggleAgentMode = () => {
    if (isHumanAgent) {
      // Switch to AI mode
      if (ws) {
        ws.close();
      }
      setIsHumanAgent(false);
      setMessages(prev => [...prev, {
        id: Date.now().toString(),
        text: '已切换到自动回复模式',
        isSent: false,
        timestamp: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }),
      }]);
    } else {
      // Switch to human agent mode
      setIsHumanAgent(true);
    }
  };

  // Toggle between customer and service role
  const toggleUserRole = () => {
    // Close existing connection if any
    if (ws) {
      ws.close();
    }
    
    const newRole = !isServiceRole;
    setIsServiceRole(newRole);
    setMessages([{
      id: Date.now().toString(),
      text: `已切换到${newRole ? '客服' : '用户'}角色`,
      isSent: false,
      timestamp: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }),
    }]);
    
    // Reconnect if in human agent mode
    if (isHumanAgent) {
      setTimeout(() => {
        connectWebSocket();
      }, 500);
    }
  };

  // Auto scroll to bottom when new messages arrive
  useEffect(() => {
    if (flatListRef.current) {
      flatListRef.current.scrollToEnd({ animated: true });
    }
  }, [messages]);

  // Handle quick action button press
  const handleQuickAction = (action: string) => {
    setInputText(action);
  };

  // Render each message item
  const renderMessageItem = ({ item }: { item: Message }) => (
    <View 
      style={[
        styles.messageBubble, 
        item.isSent ? styles.sentBubble : styles.receivedBubble
      ]}
    >
      <ResponsiveText 
        style={[
          styles.messageText,
          item.isSent ? styles.sentText : styles.receivedText
        ]}
      >
        {item.text}
      </ResponsiveText>
      <ResponsiveText style={styles.timestamp}>{item.timestamp}</ResponsiveText>
    </View>
  );

  return (
    <ResponsiveContainer style={styles.container}>
      <StatusBar backgroundColor="#4CAF50" barStyle="light-content" />
      
      {/* Header */}
      <View style={styles.header}>
        <TouchableOpacity onPress={handleBack} style={styles.backButton}>
          <Icon name="chevron-back" size={scale(22)} color="#FFF" />
        </TouchableOpacity>
        <View style={styles.headerContent}>
          <ResponsiveText style={styles.headerTitle}>
            {isServiceRole ? '客服模式' : (isHumanAgent ? '人工客服' : '智能客服')}
          </ResponsiveText>
          <ResponsiveText style={styles.headerSubtitle}>
            {isServiceRole 
              ? '您当前作为客服角色'
              : (isHumanAgent 
                ? connected ? '客服已接入，正在为您服务' : '正在连接客服...' 
                : '通常在几秒内回复')}
          </ResponsiveText>
        </View>
        <TouchableOpacity style={styles.moreButton} onPress={toggleAgentMode}>
          <MaterialIcons 
            name={isHumanAgent ? "android" : "people"} 
            size={scale(22)} 
            color="#FFF" 
          />
        </TouchableOpacity>
        <TouchableOpacity style={styles.roleButton} onPress={toggleUserRole}>
          <MaterialIcons 
            name={isServiceRole ? "person" : "headset-mic"} 
            size={scale(22)} 
            color="#FFF" 
          />
        </TouchableOpacity>
      </View>

      {/* Role Switcher Banner */}
      <View style={styles.roleSwitcherBanner}>
        <ResponsiveText style={styles.roleSwitcherText}>
          当前身份: {isServiceRole ? '客服' : '用户'}
        </ResponsiveText>
        <TouchableOpacity 
          style={styles.roleSwitcherButton} 
          onPress={toggleUserRole}
        >
          <MaterialIcons 
            name={isServiceRole ? "person" : "headset-mic"} 
            size={scale(16)} 
            color="#FFF" 
            style={styles.roleSwitcherIcon}
          />
          <ResponsiveText style={styles.roleSwitcherButtonText}>
            切换到{isServiceRole ? '用户' : '客服'}身份
          </ResponsiveText>
        </TouchableOpacity>
      </View>

      {/* Chat content */}
      <FlatList
        ref={flatListRef}
        data={messages}
        renderItem={renderMessageItem}
        keyExtractor={item => item.id}
        contentContainerStyle={styles.chatContent}
        onLayout={() => flatListRef.current?.scrollToEnd({ animated: false })}
      />

      {/* Input area */}
      <KeyboardAvoidingView
        behavior={Platform.OS === 'ios' ? 'padding' : undefined}
        keyboardVerticalOffset={Platform.OS === 'ios' ? 90 : 0}
      >
        <View style={styles.inputContainer}>
          <TouchableOpacity style={styles.attachButton}>
            <AntDesign name="plus" size={scale(22)} color="#666" />
          </TouchableOpacity>
          <TextInput
            style={styles.textInput}
            placeholder={isServiceRole 
              ? "输入消息回复用户..." 
              : (isHumanAgent ? "输入消息给客服..." : "输入消息...")}
            placeholderTextColor="#999"
            value={inputText}
            onChangeText={setInputText}
            multiline
          />
          <TouchableOpacity 
            style={[
              styles.sendButton,
              inputText.trim() === '' ? styles.disabledSendButton : {}
            ]}
            onPress={handleSend}
            disabled={inputText.trim() === ''}
          >
            <Icon name="send" size={scale(20)} color={inputText.trim() === '' ? '#CCC' : '#FFF'} />
          </TouchableOpacity>
        </View>
      </KeyboardAvoidingView>

      {/* Quick actions */}
      <View style={styles.quickActionsBar}>
        <ScrollView horizontal showsHorizontalScrollIndicator={false}>
          {isServiceRole ? (
            <>
              <TouchableOpacity 
                style={styles.quickAction}
                onPress={() => handleQuickAction('您好，请问有什么可以帮您？')}
              >
                <ResponsiveText style={styles.quickActionText}>问候语</ResponsiveText>
              </TouchableOpacity>
              <TouchableOpacity 
                style={styles.quickAction}
                onPress={() => handleQuickAction('您的订单已经在处理中')}
              >
                <ResponsiveText style={styles.quickActionText}>订单状态</ResponsiveText>
              </TouchableOpacity>
              <TouchableOpacity 
                style={[styles.quickAction, styles.humanServiceButton]}
                onPress={() => handleQuickAction('感谢您的咨询，还有其他问题吗？')}
              >
                <ResponsiveText style={styles.humanServiceText}>结束语</ResponsiveText>
              </TouchableOpacity>
            </>
          ) : (
            <>
              <TouchableOpacity 
                style={styles.quickAction}
                onPress={() => handleQuickAction('订单查询')}
              >
                <ResponsiveText style={styles.quickActionText}>订单查询</ResponsiveText>
              </TouchableOpacity>
              <TouchableOpacity 
                style={styles.quickAction}
                onPress={() => handleQuickAction('退款问题')}
              >
                <ResponsiveText style={styles.quickActionText}>退款问题</ResponsiveText>
              </TouchableOpacity>
              <TouchableOpacity 
                style={[styles.quickAction, styles.humanServiceButton]}
                onPress={() => handleQuickAction('人工服务')}
              >
                <ResponsiveText style={styles.humanServiceText}>人工服务</ResponsiveText>
              </TouchableOpacity>
              <TouchableOpacity 
                style={styles.quickAction}
                onPress={() => handleQuickAction('配送查询')}
              >
                <ResponsiveText style={styles.quickActionText}>配送查询</ResponsiveText>
              </TouchableOpacity>
            </>
          )}
        </ScrollView>
      </View>
    </ResponsiveContainer>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#F5F5F5',
  },
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingVertical: scale(12),
    paddingHorizontal: scale(15),
    backgroundColor: '#4CAF50',
  },
  headerContent: {
    flex: 1,
    marginLeft: scale(10),
  },
  headerTitle: {
    fontSize: scale(16),
    fontWeight: '600',
    color: '#FFFFFF',
  },
  headerSubtitle: {
    fontSize: scale(12),
    color: 'rgba(255, 255, 255, 0.8)',
    marginTop: scale(2),
  },
  backButton: {
    padding: scale(5),
  },
  moreButton: {
    padding: scale(5),
    marginRight: scale(8),
  },
  roleButton: {
    padding: scale(5),
    backgroundColor: 'rgba(255, 255, 255, 0.2)',
    borderRadius: scale(5),
  },
  roleSwitcherBanner: {
    backgroundColor: '#E8F5E9',
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingHorizontal: scale(15),
    paddingVertical: scale(8),
    borderBottomWidth: 1,
    borderBottomColor: '#CCECE0',
  },
  roleSwitcherText: {
    fontSize: scale(14),
    color: '#2E7D32',
    fontWeight: '500',
  },
  roleSwitcherButton: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: '#4CAF50',
    paddingHorizontal: scale(12),
    paddingVertical: scale(6),
    borderRadius: scale(16),
  },
  roleSwitcherIcon: {
    marginRight: scale(5),
  },
  roleSwitcherButtonText: {
    color: '#FFFFFF',
    fontSize: scale(13),
    fontWeight: '500',
  },
  chatContent: {
    paddingHorizontal: scale(15),
    paddingVertical: scale(10),
    paddingBottom: scale(20),
  },
  messageBubble: {
    maxWidth: '75%',
    padding: scale(12),
    borderRadius: scale(12),
    marginVertical: scale(4),
  },
  sentBubble: {
    alignSelf: 'flex-end',
    backgroundColor: '#DCF8C6',
    borderTopRightRadius: scale(4),
  },
  receivedBubble: {
    alignSelf: 'flex-start',
    backgroundColor: '#FFFFFF',
    borderTopLeftRadius: scale(4),
  },
  messageText: {
    fontSize: scale(14),
    lineHeight: scale(20),
  },
  sentText: {
    color: '#303030',
  },
  receivedText: {
    color: '#303030',
  },
  timestamp: {
    fontSize: scale(10),
    color: '#999',
    alignSelf: 'flex-end',
    marginTop: scale(4),
  },
  inputContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: '#FFFFFF',
    borderTopWidth: 1,
    borderTopColor: '#E5E5E5',
    paddingHorizontal: scale(10),
    paddingVertical: scale(8),
  },
  attachButton: {
    width: scale(36),
    height: scale(36),
    borderRadius: scale(18),
    backgroundColor: '#F0F0F0',
    justifyContent: 'center',
    alignItems: 'center',
    marginRight: scale(8),
  },
  textInput: {
    flex: 1,
    backgroundColor: '#F0F0F0',
    borderRadius: scale(18),
    paddingHorizontal: scale(15),
    paddingVertical: scale(8),
    maxHeight: scale(100),
    fontSize: scale(14),
    color: '#333',
  },
  sendButton: {
    width: scale(36),
    height: scale(36),
    borderRadius: scale(18),
    backgroundColor: '#4CAF50',
    justifyContent: 'center',
    alignItems: 'center',
    marginLeft: scale(8),
  },
  disabledSendButton: {
    backgroundColor: '#E0E0E0',
  },
  quickActionsBar: {
    backgroundColor: '#FFFFFF',
    paddingVertical: scale(10),
    paddingHorizontal: scale(10),
    borderTopWidth: 1,
    borderTopColor: '#F0F0F0',
  },
  quickAction: {
    backgroundColor: '#F0F0F0',
    paddingHorizontal: scale(15),
    paddingVertical: scale(8),
    borderRadius: scale(16),
    marginRight: scale(10),
  },
  quickActionText: {
    fontSize: scale(13),
    color: '#555',
  },
  humanServiceButton: {
    backgroundColor: 'rgba(76, 175, 80, 0.1)',
    borderWidth: 1,
    borderColor: '#4CAF50',
  },
  humanServiceText: {
    fontSize: scale(13),
    color: '#4CAF50',
    fontWeight: '500',
  }
});

export default ChatScreen; 